package com.hangxintong.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.hangxintong.common.exception.ClientErrorCodeMark;
import com.hangxintong.common.exception.ClientException;
import com.hangxintong.common.base.entity.LmUser;
import com.hangxintong.common.base.service.UserService;
import com.hangxintong.common.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lvyanfei
 * @date 2021-01-04
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            return true;
        }

        //拦截逻辑a
        String token= request.getHeader("token");


        if (ObjectUtil.isEmpty(token)) {
            throw new ClientException(ClientErrorCodeMark.Code.UNAUTHORIZED_ERROR);
        } else {
            String account = JWT.decode(token).getAudience().get(0);
            LmUser lmUser = userService.findByMobile(account);
            if(lmUser!=null&&ObjectUtil.isEmpty(lmUser)){
                throw new ClientException(ClientErrorCodeMark.Code.FORBIDDEN_ERROR);
            }else{
//                request.setAttribute("user",lmUser);
                request.getSession().setAttribute("user",lmUser);
//                Object object = redisUtil.get("userToken" + lmUser.getId());
                request.setAttribute("user",lmUser);
                return true;
//                if(ObjectUtil.isEmpty(object)){
//                    throw new ClientException(ClientErrorCodeMark.Code.FORBIDDEN_ERROR);
//                }else{
//                    request.setAttribute("user",lmUser);
//                    return true;
//                }
            }
        }
    }
}
